<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /* 
            回溯本质是穷举

            ①确定终止条件
            当sum==target
            ②确定遍历范围
            因为每个数字可以重复选，所以需要个start确定选了哪个
            ③优化 剪枝 大于target直接return
            */
            var combinationSum = function (candidates, target) {
                let res = []

                candidates.sort((a, b) => a - b)
                function backTacking(start, path, sum) {
                    if (sum > target) return
                    if (sum == target) {
                        return res.push([...path])
                    }
                    for (let i = start; i < candidates.length; i++) {
                        path.push(candidates[i])
                        backTacking(i, path, sum + candidates[i])
                        path.pop()
                    }
                }
                backTacking(0, [], 0)
                return res
            }
            combinationSum()
        </script>
    </body>
</html>
